package com.by.rule;


import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    //JUC包下，线程安装的Integer
    private static AtomicInteger count = new AtomicInteger(0);
    private Server server = null;
    @Override
    @SneakyThrows
    public Server choose(Object key) {
        BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
        //获取服务名称
        String serverName = loadBalancer.getName();
        NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
        List<Instance> allInstances = namingService.getAllInstances(serverName, true);
        //获取权重最大的机器
        Instance maxInstance = allInstances.stream().max(Comparator.comparing(Instance::getWeight)).get();
        //获取权重最小的机器
        Instance minInstance = allInstances.stream().min(Comparator.comparing(Instance::getWeight)).get();
        //计数器
        int count2 = count.addAndGet(1);
        int mod = count2 % 5; //取模运算  5,10,15，20,25 ...
        if(mod == 0){  //当次数是5的倍数的时候，mod就是0,
            server = new Server(minInstance.getIp(),minInstance.getPort());
        } else  {
            //mod 是 1,2,3,4 的时候打到权重高的这个机器上
            server = new Server(maxInstance.getIp(),maxInstance.getPort());
        }
        return server;
    }


    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }
}
